package com.genesis.yunnanji.view;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.genesis.yunnanji.Constants;

import com.genesis.yunnanji.R;
import com.genesis.yunnanji.adapter.DialogFragmentGoodsSizeAdapter;
import com.genesis.yunnanji.bean.AddTrolleyBean;
import com.genesis.yunnanji.bean.BaseBean;
import com.genesis.yunnanji.bean.GoodsAttrBean;
import com.genesis.yunnanji.bean.GoodsAttrChildBean;
import com.genesis.yunnanji.bean.GoodsInfoBean;
import com.genesis.yunnanji.bean.MessageEventBean;
import com.genesis.yunnanji.bean.NoResultBean;
import com.genesis.yunnanji.bean.RepertoryNumBean;
import com.genesis.yunnanji.utils.NetUtils;
import com.timmy.tdialog.TDialog;
import com.timmy.tdialog.base.BindViewHolder;
import com.timmy.tdialog.listener.OnBindViewListener;
import com.timmy.tdialog.listener.OnViewClickListener;
import com.youth.xframe.widget.XToast;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.CallBackProxy;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;

import org.bining.footstone.utils.SharedUtils;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.RequestBody;

/**
 * 创建日期：2018/10/11 001117:55
 * 作者：Kite
 * 描述：商品详情
 */
public class GoodsDetailsActivity extends BaseActivity {

    @BindView(R.id.tv_collection)
    TextView tvCollection;

    @BindView(R.id.wv_details)
    WebView wvDetails;

    private String goodsID = "";

    private boolean isClick = true;

    private TDialog mTDialog;//弹出布局

    private List<GoodsAttrBean> mStorageBackgroundList = new ArrayList<>();

    private int mTotalNum = 1;//商品数量

    private int mRepertoryNum = 0;//库存数量

    public GoodsInfoBean.InfosBean mInfos;
    public List<GoodsInfoBean.PictureBean> mPicture;
    public List<GoodsInfoBean.StockBean> mStock;

    private String mGoodsSKUID = "";//后台需要的skuid

    @Override
    public int getLayoutId() {
        return R.layout.activity_goods_details;
    }

    public GoodsInfoBean goodsInfoBean;

    @Override
    public void initView() {
        super.initView();
        setTitle("产品详情");
        Bundle bundle = null;
        if (bundle == null) {
            goodsID = getIntent().getStringExtra("p0");
            getGoodsInfo(goodsID);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getID(RepertoryNumBean bean) {
        if (bean.getSkuID() != null) {
            mGoodsSKUID = bean.getSkuID();
            mRepertoryNum = Integer.parseInt(bean.getNum());
//            XToast.info(str);
        }
    }

    @OnClick({R.id.tv_customer, R.id.tv_collection, R.id.tv_trolley, R.id.tv_add_trolley, R.id.tv_buy})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_customer:
                break;
            case R.id.tv_collection:
                if (isClick) {
                    addCollection(goodsID);
                } else {
                    cancelCollection(goodsID);
                }
                break;
            case R.id.tv_trolley:
                EventBus.getDefault().post("trolley");
                Intent intent = new Intent(this, HomePageActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_add_trolley:
                mTotalNum = 1;
                mStorageBackgroundList.clear();
                mTDialog.show();
                break;
            case R.id.tv_buy:
                mTotalNum = 1;
                mStorageBackgroundList.clear();
                mTDialog.show();
                break;
        }
    }

    private void defaultState(TextView textView, int drawableRes) {
        Drawable drawable = getResources().getDrawable(drawableRes);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        textView.setCompoundDrawables(null, drawable, null, null);
    }

    public TextView dialogTitle;
    public TextView dialogPrice;
    public TextView dialogStock;
    public ImageView dialogImage;

    private void goodsSize() {
        mTDialog = new TDialog.Builder(getSupportFragmentManager())
                .setLayoutRes(R.layout.dialog_fragment_goods_size)
                .setScreenWidthAspect(GoodsDetailsActivity.this, 1.0f)
                .setScreenHeightAspect(GoodsDetailsActivity.this, 0.6f)
                .setGravity(Gravity.BOTTOM)
                .setDialogAnimationRes(R.style.dialog_fragment_bottom_anim)
                .addOnClickListener(R.id.iv_close, R.id.btn_sure)
                .setOnBindViewListener(new OnBindViewListener() {   //通过BindViewHolder拿到控件对象,进行修改
                    @Override
                    public void bindView(BindViewHolder bindViewHolder) {
                        RecyclerView recyclerView = (RecyclerView) bindViewHolder.getView(R.id.rc_goods_size);
                        dialogTitle = bindViewHolder.getView(R.id.tv_title);
                        dialogPrice = bindViewHolder.getView(R.id.tv_price);
                        dialogStock = bindViewHolder.getView(R.id.tv_inventory);
                        dialogImage = bindViewHolder.getView(R.id.iv_goods);

                        TextView dialogAdd = bindViewHolder.getView(R.id.tv_add);
                        TextView dialogSub = bindViewHolder.getView(R.id.tv_sub);
                        final TextView dialogNum = bindViewHolder.getView(R.id.tv_commodity_show_num);

                        dialogAdd.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (mRepertoryNum < mTotalNum) {
                                    XToast.warning("已超过库存上线");
                                    return;
                                }
                                dialogNum.setText("" + ++mTotalNum);
//                                XToast.info((Double.valueOf(dialogPrice.getText().toString()) * mTotalNum) + "");
                            }
                        });

                        dialogSub.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (mTotalNum == 1) {
                                    XToast.warning("至少选择一件商品");
                                    return;
                                }
                                dialogNum.setText("" + --mTotalNum);
//                                XToast.info((Double.valueOf(dialogPrice.getText().toString()) * mTotalNum) + "");
                            }
                        });

                        dialogTitle.setText(mInfos.getProduct_name());
                        dialogPrice.setText(mInfos.getSale_price());
                        dialogStock.setText(mInfos.getStocknums());
                        Glide.with(GoodsDetailsActivity.this)
                                .load(Constants.PIC_ADMIN + mInfos.getCover_img())
                                .into(dialogImage);

                        recyclerView.setLayoutManager(new LinearLayoutManager(GoodsDetailsActivity.this));
                        DialogFragmentGoodsSizeAdapter dialogAdapter = new DialogFragmentGoodsSizeAdapter(R.layout.item_goods_size_parent, mStorageBackgroundList);
                        dialogAdapter.bindActivity(GoodsDetailsActivity.this);
                        dialogAdapter.bindToRecyclerView(recyclerView);
                        mStorageBackgroundList.add(new GoodsAttrBean("型号", new ArrayList<GoodsAttrChildBean>()));
                        mStorageBackgroundList.add(new GoodsAttrBean("规格", new ArrayList<GoodsAttrChildBean>()));
                        for (GoodsInfoBean.StockBean s :
                                goodsInfoBean.getStock()) {
                            if (mStorageBackgroundList.get(0).getList().size() == 0) {
                                mStorageBackgroundList.get(0).getList().add(new GoodsAttrChildBean(s.getColor_id(), s.getColor_name()));
                            } else {
                                for (int i = 0; i < mStorageBackgroundList.get(0).getList().size(); i++) {
                                    if (mStorageBackgroundList.get(0).getList().get(i).getId().equals(s.getColor_id())) {
                                        break;
                                    }
                                    if (i == mStorageBackgroundList.get(0).getList().size() - 1) {
                                        mStorageBackgroundList.get(0).getList().add(new GoodsAttrChildBean(s.getColor_id(), s.getColor_name()));
                                    }
                                }
                            }
                            if (mStorageBackgroundList.get(1).getList().size() == 0) {
                                mStorageBackgroundList.get(1).getList().add(new GoodsAttrChildBean(s.getSize_id(), s.getSize_name()));
                            } else {
                                for (int i = 0; i < mStorageBackgroundList.get(1).getList().size(); i++) {
                                    if (mStorageBackgroundList.get(1).getList().get(i).getId().equals(s.getSize_id())) {
                                        break;
                                    }
                                    if (i == mStorageBackgroundList.get(1).getList().size() - 1) {
                                        mStorageBackgroundList.get(1).getList().add(new GoodsAttrChildBean(s.getSize_id(), s.getSize_name()));
                                    }
                                }
                            }

                        }

                    }
                })
                .setOnViewClickListener(new OnViewClickListener() {
                    @Override
                    public void onViewClick(BindViewHolder viewHolder, View view, TDialog tDialog) {
                        switch (view.getId()) {
                            case R.id.iv_close:
                                tDialog.dismiss();
                                break;
                            case R.id.btn_sure:
                                if (mGoodsSKUID.equals("")) {
                                    XToast.warning("请选择规格和型号");
                                    return;
                                }
                                if (mRepertoryNum < mTotalNum) {
                                    XToast.warning("已超过库存上线");
                                    return;
                                }
                                addTrolley();
                                tDialog.dismiss();
                                break;
                        }
                    }
                })
                .create();
    }

    /**
     * 加入收藏
     *
     * @param productid
     */
    private void addCollection(String productid) {
        JSONObject params = new JSONObject();
        try {
            params.put("productid", productid);
            params.put("__apptoken__", SharedUtils.getString(Constants.USER_TOKEN));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = NetUtils.initNet(params);
        EasyHttp.post(Constants.MEMBER_ADD_COLLECT)
//                .baseUrl(Constants.MAIN_ADMIN)
                .requestBody(requestBody)
                .execute(new CallBackProxy<BaseBean<NoResultBean>, NoResultBean>(new SimpleCallBack<NoResultBean>() {
                    @Override
                    public void onError(ApiException e) {
                        XToast.error(e.getMessage());
                    }

                    @Override
                    public void onSuccess(NoResultBean bean) {
                        EventBus.getDefault().post(new MessageEventBean(true));
                        isClick = false;
                        defaultState(tvCollection, R.drawable.details_incollection);
                        XToast.success("收藏成功！");
                    }
                }) {
                });
    }

    /**
     * 取消收藏
     */
    private void cancelCollection(String id) {
        JSONObject params = new JSONObject();
        try {
            params.put("id", id);
            params.put("__apptoken__", SharedUtils.getString(Constants.USER_TOKEN));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = NetUtils.initNet(params);
        EasyHttp.post(Constants.MEMBER_REMOVE_COLLECT)
//                .baseUrl(Constants.MAIN_ADMIN)
                .requestBody(requestBody)
                .execute(new CallBackProxy<BaseBean<NoResultBean>, NoResultBean>(new SimpleCallBack<NoResultBean>() {
                    @Override
                    public void onError(ApiException e) {
                        XToast.error(e.getMessage());
                    }

                    @Override
                    public void onSuccess(NoResultBean bean) {
                        EventBus.getDefault().post(new MessageEventBean(true));
                        XToast.success("收藏已取消！");
                        isClick = true;
                        defaultState(tvCollection, R.drawable.details_outcollection);
                    }
                }) {
                });
    }

    /**
     * 各种信息详情
     *
     * @param id
     */
    private void getGoodsInfo(String id) {
        JSONObject params = new JSONObject();
        try {
            params.put("id", id);
            params.put("__apptoken__", SharedUtils.getString(Constants.USER_TOKEN));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = NetUtils.initNet(params);
        EasyHttp.post(Constants.INDEX_PRODUCTVIEW)
//                .baseUrl(Constants.MAIN_ADMIN)
                .requestBody(requestBody)
                .execute(new CallBackProxy<BaseBean<GoodsInfoBean>, GoodsInfoBean>(new SimpleCallBack<GoodsInfoBean>() {
                    @Override
                    public void onError(ApiException e) {
                        XToast.error(e.getMessage());
                    }

                    @Override
                    public void onSuccess(GoodsInfoBean bean) {
                        if (bean.getInfos().getIscollect().equals("on")) {
                            isClick = false;
                            defaultState(tvCollection, R.drawable.details_incollection);
                        } else {
                            isClick = true;
                            defaultState(tvCollection, R.drawable.details_outcollection);
                        }
                        goodsInfoBean = bean;
                        mInfos = bean.getInfos();
                        mPicture = bean.getPicture();
                        mStock = bean.getStock();
                        goodsSize();
                    }
                }) {
                });
    }

    /**
     * 加入购物车
     */
    private void addTrolley() {
        JSONObject params = new JSONObject();
        try {
            params.put("stockid", mGoodsSKUID);
            params.put("nums", mTotalNum);
            params.put("__apptoken__", SharedUtils.getString(Constants.USER_TOKEN));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody requestBody = NetUtils.initNet(params);
        EasyHttp.post(Constants.CART_ADD)
//                .baseUrl(Constants.MAIN_ADMIN)
                .requestBody(requestBody)
                .execute(new CallBackProxy<BaseBean<AddTrolleyBean>, AddTrolleyBean>(new SimpleCallBack<AddTrolleyBean>() {
                    @Override
                    public void onError(ApiException e) {
                        XToast.error(e.getMessage());
                    }

                    @Override
                    public void onSuccess(AddTrolleyBean bean) {
                        String cartNums = bean.getCart_nums();
                        EventBus.getDefault().post(new MessageEventBean(true));
                        XToast.success("添加成功");
                    }
                }) {
                });
    }

}


